package com.hello.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletContext;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController implements ServletContextAware {
	private ServletContext servletContext;
	private final int BUFFER_SIZE = 512 * 2;
	
	@RequestMapping(value = "/fileUpload.html", method = RequestMethod.GET)
	public String showFileUploadForm(ModelMap model) {
		model.addAttribute("imageFileName", null);
		model.addAttribute("caption", null);
		return "fileUpload";
	}
	
	@RequestMapping(value = "/uploadSuccess.html", method = RequestMethod.GET)
	public String showSuccessForm() {
		return "uploadSuccess";
	}
	
	@RequestMapping(value = "/upload.html", method = RequestMethod.POST)
	public ModelMap handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
		if(!file.isEmpty()) {
			try {
				BufferedOutputStream out = null;
				try {
					byte[] bytes = file.getBytes();
					String imageFileName = "p_large_" + new Date().getTime() + getFileExtension(file.getOriginalFilename());
					File imageFile = new File(getServletContext().getRealPath("/UploadImages") + "/" + imageFileName);
					out = new BufferedOutputStream(new FileOutputStream(imageFile), BUFFER_SIZE);
					out.write(bytes);
					
					ModelMap model = new ModelMap();
					model.addAttribute("imageFileName", imageFileName);
					model.addAttribute("caption", name);
					return model;
				} finally {
					if(null != out) {
						out.close();
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
	
	private static String getFileExtension(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		// TODO Auto-generated method stub
		this.servletContext = servletContext;
	}
	
	public ServletContext getServletContext() {
		return this.servletContext;
	}
}
